package org.orbroker

import org.orbroker.exception._
import org.orbroker.conv._
import org.orbroker.adapt.BrokerAdapter
import org.orbroker.callback.ExecutionCallback

import org.apache.velocity._
import org.apache.velocity.app.VelocityEngine
import org.apache.velocity.context._
import org.apache.velocity.runtime.RuntimeInstance
import org.apache.velocity.runtime.parser.node.SimpleNode
import SQLStatement._
import java.io.StringWriter

private[orbroker]class VelocityStatement(
    id: Symbol,
    velocitySQL: Seq[String],
    trimSQL: Boolean,
    callback: ExecutionCallback,
    adapter: BrokerAdapter,
    runtime: RuntimeInstance) extends SQLStatement(id, callback, adapter) {

  private val template = new ThreadLocal[SimpleNode] {
    override def initialValue = {
      val temp = runtime.parse(velocitySQL.mkString(EOL), id.toString)
      temp.init(null, runtime)
      temp
    }
  }

  override def statement(parms: Map[String, Any]) = {
    val context = new VelocityContext(toJavaMap(parms))
    val ctxAdapter = new InternalContextAdapterImpl(context)
    val writer = new StringWriter
    template.get.render(ctxAdapter, writer)
    SQLStatement.parseSQL(id, writer, trimSQL, adapter)
  }
}

